package com.fas.hehe.system.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.fas.core.BaseService;
import com.fas.hehe.system.model.User;

public class UserService extends BaseService {
	// 修改密码
	public void changePassword(Long userId, String newPassword) {

	}

	// 根据用户名查找用户
	public User findByUsername(String username) {
		String sql = "select * from sys_user where username = ?";
		return User.dao.findFirst(sql, username);
	}

	// 根据用户名查找其角色
	public Set<String> findRoles(String username) {
		User user = findByUsername(username);
		if (user == null) {
			return Collections.EMPTY_SET;
		}

		String roleIdsStr = user.getStr("role_ids");
		if (StringUtils.isEmpty(roleIdsStr)) {
			return Collections.EMPTY_SET;
		}

		List<Long> roleId = new ArrayList<Long>(); // 拥有的角色列表
		String[] roleIdStrs = roleIdsStr.split(",");
		for (String roleIdStr : roleIdStrs) {
			if (StringUtils.isEmpty(roleIdStr)) {
				continue;
			}
			roleId.add(Long.valueOf(roleIdStr));
		}

		return new RoleService().findRoles(roleId.toArray(new Long[0]));
	}

	// 根据用户名查找其权限
	public Set<String> findPermissions(String username) {
		User user = findByUsername(username);
		if (user == null) {
			return Collections.EMPTY_SET;
		}

		String roleIdsStr = user.getStr("role_ids");
		if (StringUtils.isEmpty(roleIdsStr)) {
			return Collections.EMPTY_SET;
		}

		List<Long> roleId = new ArrayList<Long>(); // 拥有的角色列表
		String[] roleIdStrs = roleIdsStr.split(",");
		for (String roleIdStr : roleIdStrs) {
			if (StringUtils.isEmpty(roleIdStr)) {
				continue;
			}
			roleId.add(Long.valueOf(roleIdStr));
		}
		return new RoleService().findPermissions(roleId.toArray(new Long[0]));
	}
}
